package com.ktjy.springthymeleaf.controller;


import com.ktjy.springthymeleaf.entity.User;
import com.ktjy.springthymeleaf.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @return 13141
 * 2025/7/16
 * 08:43
 */
@Controller
// @RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    @RequestMapping("/list")
    public List<User> list() {
        return userService.list();
    }

    @RequestMapping(value = "/dologin")
    public String dologin(String usrName, String usrPassword, HttpServletRequest request) {
        User user = userService.login(usrName, usrPassword);
        if (user != null) {
            request.getSession().setAttribute("loginUser", user);
            return "main";
        } else {
            request.setAttribute("message", "登录失败，用户名或密码错误！");
            return "login";
        }
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "login";
    }

    /**
     * 查询所有用户
     * @param usrName
     * @param roleId
     * @param model
     * @return
     */
    @GetMapping(value = "/user/list")
    public String findUsers(String usrName, Long roleId, Model model) {
        List<User>  list = userService.findAllUsers();
        model.addAttribute("userPager", list);
        // 判断用户是否登录
        if (list == null) {
            return "login";
        }
        return "user/list";
    }
}
